using System;
using System.Collections.Generic;
using System.Text;
using Koda.VisualStudio.Integration;
using Koda.VisualStudio;
using EnvDTE80;
using Koda.Search;
using Koda.UI;
using System.Windows.Forms;
using Koda.Utils;
using Koda.Search.Finders;
using EnvDTE;

namespace Koda.Commands
{
    public class GotoImplementorCommand : VsCommand
    {
        public GotoImplementorCommand() : base("Go to implementor(s)", "Code Window", 1)
        {
        }

        public override bool OnQueryStatus(VsCommandEventArgs e)
        {
            //if (VsCodeModelUtilities.GetInterfaceFromSelection(e.DTE) != null)
                return true;
            //return false;
        }

        public override void OnExecute(VsCommandEventArgs e)
        {
            CodeInterface2 codeInterface = VsCodeModelUtilities.GetInterfaceFromSelection(e.DTE);
            if (codeInterface == null)
            {
                TextSelection ts = (TextSelection)e.DTE.ActiveDocument.Selection;
                MessageBox.Show(ts.Text);

                CodeFunction2 cf = VsCodeModelUtilities.GetCodeElementFromSelection(e.DTE, vsCMElement.vsCMElementFunction) as CodeFunction2;
                if (cf != null)
                    MessageBox.Show(cf.Name);
            }
            else
            {
                IVsItemFinder finder = new ImplementorFinder(e.DTE);
                int numberOfItemsFound = finder.Search(codeInterface.Name);

                if (numberOfItemsFound == 1)
                {
                    finder.OpenItem(finder.Result[0]);
                }
                else if (numberOfItemsFound > 1)
                {
                    OpenForm form = new OpenForm(finder);
                    form.KeywordTextBoxEnabled = false;
                    form.ShowDialog();
                }
                else
                {
                    MessageBox.Show(String.Format("Couldn't find any class implementing interface '{0}'", codeInterface.Name));
                }
            }
        }
    }
}
